import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';

/// 权限申请工具类
/// 按需申请权限，而不是在应用启动时统一申请
class PermissionApply {
  /// 申请位置权限
  /// 用于：附近选项卡、地图页面
  static Future<bool> requestLocationPermission() async {
    PermissionStatus status = await Permission.location.status;
    Get.log('位置权限状态: $status');
    
    if (status.isGranted) {
      return true;
    }
    
    if (status.isDenied) {
      status = await Permission.location.request();
      Get.log('位置权限申请结果: $status');
      return status.isGranted;
    }
    
    if (status.isPermanentlyDenied) {
      Get.log('位置权限被永久拒绝，需要打开设置');
      // 可以弹出对话框提示用户
      bool shouldOpen = await _showPermissionDialog('位置', '查看附近的故事');
      if (shouldOpen) {
        await openAppSettings();
      }
      return false;
    }
    
    return false;
  }
  
  /// 申请相机权限
  /// 用于：发布图文故事、发布视频故事
  static Future<bool> requestCameraPermission() async {
    PermissionStatus status = await Permission.camera.status;
    Get.log('相机权限状态: $status');
    
    if (status.isGranted) {
      return true;
    }
    
    if (status.isDenied) {
      status = await Permission.camera.request();
      Get.log('相机权限申请结果: $status');
      return status.isGranted;
    }
    
    if (status.isPermanentlyDenied) {
      Get.log('相机权限被永久拒绝，需要打开设置');
      bool shouldOpen = await _showPermissionDialog('相机', '拍摄照片或视频');
      if (shouldOpen) {
        await openAppSettings();
      }
      return false;
    }
    
    return false;
  }
  
  /// 申请照片权限
  /// 用于：发布图文故事、发布视频故事、选择图片
  static Future<bool> requestPhotosPermission() async {
    PermissionStatus status = await Permission.photos.status;
    Get.log('照片权限状态: $status');
    
    if (status.isGranted) {
      return true;
    }
    
    if (status.isDenied) {
      status = await Permission.photos.request();
      Get.log('照片权限申请结果: $status');
      return status.isGranted;
    }
    
    if (status.isPermanentlyDenied) {
      Get.log('照片权限被永久拒绝，需要打开设置');
      bool shouldOpen = await _showPermissionDialog('照片', '选择照片');
      if (shouldOpen) {
        await openAppSettings();
      }
      return false;
    }
    
    return false;
  }
  
  /// 申请视频权限
  /// 用于：发布视频故事、选择视频
  /// Android 13+ 使用 photos 权限，Android 12- 使用 storage 权限
  static Future<bool> requestVideosPermission() async {
    // Android 13+ (API 33+) 使用 photos 权限，它包含了图片和视频的访问权限
    // Android 12- 使用 videos 权限
    PermissionStatus status;
    
    // 先尝试 photos 权限（Android 13+ 推荐）
    status = await Permission.photos.status;
    Get.log('照片权限状态（用于视频）: $status');
    
    if (status.isGranted || status.isLimited) {
      return true;
    }
    
    if (status.isDenied) {
      status = await Permission.photos.request();
      Get.log('照片权限申请结果（用于视频）: $status');
      if (status.isGranted || status.isLimited) {
        return true;
      }
    }
    
    // 如果 photos 权限失败，尝试 videos 权限（Android 12- 兼容）
    status = await Permission.videos.status;
    Get.log('视频权限状态: $status');
    
    if (status.isGranted) {
      return true;
    }
    
    if (status.isDenied) {
      status = await Permission.videos.request();
      Get.log('视频权限申请结果: $status');
      if (status.isGranted) {
        return true;
      }
    }
    
    if (status.isPermanentlyDenied) {
      Get.log('视频权限被永久拒绝，需要打开设置');
      bool shouldOpen = await _showPermissionDialog('照片和视频', '选择视频');
      if (shouldOpen) {
        await openAppSettings();
      }
      return false;
    }
    
    return false;
  }
  
  /// 申请麦克风权限
  /// 用于：语音消息、视频通话
  static Future<bool> requestMicrophonePermission() async {
    PermissionStatus status = await Permission.microphone.status;
    Get.log('麦克风权限状态: $status');
    
    if (status.isGranted) {
      return true;
    }
    
    if (status.isDenied) {
      status = await Permission.microphone.request();
      Get.log('麦克风权限申请结果: $status');
      return status.isGranted;
    }
    
    if (status.isPermanentlyDenied) {
      Get.log('麦克风权限被永久拒绝，需要打开设置');
      bool shouldOpen = await _showPermissionDialog('麦克风', '录制语音');
      if (shouldOpen) {
        await openAppSettings();
      }
      return false;
    }
    
    return false;
  }
  
  /// 申请存储权限
  /// 用于：保存图片、保存视频
  static Future<bool> requestStoragePermission() async {
    PermissionStatus status = await Permission.manageExternalStorage.status;
    Get.log('存储权限状态: $status');
    
    if (status.isGranted) {
      return true;
    }
    
    if (status.isDenied) {
      status = await Permission.manageExternalStorage.request();
      Get.log('存储权限申请结果: $status');
      return status.isGranted;
    }
    
    if (status.isPermanentlyDenied) {
      Get.log('存储权限被永久拒绝，需要打开设置');
      bool shouldOpen = await _showPermissionDialog('存储', '保存文件');
      if (shouldOpen) {
        await openAppSettings();
      }
      return false;
    }
    
    return false;
  }
  
  /// 显示权限说明对话框
  /// 当权限被永久拒绝时，提示用户打开设置
  static Future<bool> _showPermissionDialog(String permissionName, String usage) async {
    return await Get.dialog<bool>(
      AlertDialog(
        title: Text('需要$permissionName权限'),
        content: Text('为了$usage，需要授予$permissionName权限。\n\n请在设置中手动开启权限。'),
        actions: [
          TextButton(
            onPressed: () => Get.back(result: false),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () => Get.back(result: true),
            child: const Text('去设置'),
          ),
        ],
      ),
      barrierDismissible: false,
    ) ?? false;
  }
  
  /// 【已弃用】统一申请所有权限（不推荐）
  /// 建议使用按需申请的方式
  @deprecated
  static void requestPermission() async {
    // 申请权限
    var status = await Permission.camera.status;
    if (status.isDenied) {
      await Permission.camera.request();
    }
    var status1 = await Permission.photos.status;
    if (status1.isDenied) {
      await Permission.photos.request();
    }
    var status2 = await Permission.videos.status;
    if (status2.isDenied) {
      await Permission.videos.request();
    }
    await getPermissionStatus();
    var status3 = await Permission.manageExternalStorage.status;
    if (status3.isDenied) {
      await Permission.manageExternalStorage.request();
    }
  }
}

/// 获取权限状态
/// 【已弃用】建议使用 PermissionApply 中的具体方法
@deprecated
Future<bool> getPermissionStatus() async {
  Permission permission = Permission.microphone;
  //granted 通过，denied 被拒绝，permanentlyDenied 拒绝且不在提示
  PermissionStatus status = await permission.status;
  Get.log('permission status: $status');
  if (status.isGranted) {
    return true;
  } else if (status.isDenied) {
    requestPermission(permission);
  } else if (status.isPermanentlyDenied) {
    openAppSettings();
  } else if (status.isRestricted) {
    requestPermission(permission);
  } else {}
  return false;
}

/// 申请权限
/// 【已弃用】建议使用 PermissionApply 中的具体方法
@deprecated
void requestPermission(Permission permission) async {
  Get.log('requestPermission');
  PermissionStatus status = await permission.request();
  if (status.isPermanentlyDenied) {
    openAppSettings();
  }
}
